<?php
/**
 * (logic) （临时转正式）Payment销售订单
 */
namespace App\Logic\MonthlyReport\ParseTmp;

use App\Models\Basics\SysCountry;
use App\Models\MonthlyReport\Payment\PaymentOrder;
use App\Models\MonthlyReport\Tmp\TmpPSales;
use Illuminate\Support\Facades\DB;
class ParsePaymentOrder
{
    public static function exeParse($date){
        ini_set('memory_limit', '200M');
        set_time_limit(0);
        //临时
        $lines = [];
        TmpPSales::query()->where('type','Order')
            ->where('report_date',$date)
            ->select('country','order_id','fulfillment','total')
            ->orderBy('id')
            ->chunk(2000, function ($items) use (&$lines){
                foreach ($items as $item){
                    $key = $item->country.'_'.$item->order_id.'_'.$item->fulfillment;
                    if(!array_key_exists($key,$lines)){
                        $lines[$key] = $item->total;
                    }else{
                        $lines[$key] += $item->total;
                    }
                }
            });
        $i = 0;
        $num = 1000;
        $countryArr = [];
        while(true){
            if(empty($lines))break;
            $_lines = array_splice($lines,$i,$num);
            $paymentOrders = [];
            foreach ($_lines as $key => $total){
                list($country,$orderId,$fulfillment) = explode('_',$key);
                if(!array_key_exists($country,$countryArr)){
                    $_countryId = SysCountry::getIdByCountry($country);
                    $countryArr[$country] = $_countryId ?: 0;
                }
                $countryId = $countryArr[$country];
                $fulfillmentType = self::_getFulfillmentType($fulfillment);

                //正式
                $paymentOrder = PaymentOrder::query()->where('report_date',$date)
                    ->where('country_id',$countryId)
                    ->where('order_id',$orderId)
                    ->where('fulfillment_type',$fulfillmentType)
                    ->first();
                if($paymentOrder){
                    $paymentOrder->total = $total;
                    $paymentOrder->save();
                }else{
                    $_date = date('Y-m-d H:i:s');
                    $paymentOrders[] = [
                        'report_date' => $date,
                        'country_id' => $countryId,
                        'order_id' => $orderId,
                        'fulfillment_type' => $fulfillmentType,
                        'total' => $total,
                        'created_at' => $_date,
                        'updated_at' => $_date
                    ];
                }
            }
            if(!empty($paymentOrders)){
                DB::table('mr_payment_order')->insert($paymentOrders);
            }
        }
    }

    private static function _getFulfillmentType($fulfillment){
        if($fulfillment == 'AMAZON'){
            return 1;
        }else{
            return 2;
        }
    }
}
